

// ----------------------------------------------------------

// 將canvas的圖轉為圖檔
function changeToImage()
{
    //var img = document.getElementById("testImage");
    //gContext.drawImage( img, 0, 0 );
    
    //cleanCanvas(); // 畫面清空
    //drawRectangle( 0, 0, 100, 100, "green" );
    /*
    try {
    
    // save canvas image as data url (png format by default)
    var dataURL = gCanvas.toDataURL( "123.png" );
    printDebug( dataURL );
    document.getElementById( "canvasImg" ).src = dataURL;
    
    }
    catch ( err )
    {
        printError( err.stack );
    }
    */
    try {
    
    var dataURL = gCanvas.toDataURL();
    var canvasData = readWholeCanvasData(gCanvas);
    
    var strData = createBMP( canvasData );
    
    //saveFile( strData );
    
    dataURL = makeDataURI(createBMP( canvasData ), "image/bmp");
    
    //printDebug( dataURL.length );
    
    //makeImageObject(makeDataURI(dataURL, "image/bmp"));
    
    //saveFile(makeDataURI(strImgData, strDownloadMime));
    
    //var beginIndex = dataURL.indexOf( MOTION_GAP ) + 1;
    
    //var decode = decode64( dataURL.substring( beginIndex, dataURL.length ) );
    //var encode = encode64( decode );
    //printDebug( dataURL );
    //printDebug( encode );

    // set canvasImg image src to dataURL
    // so it can be saved as an image
    document.getElementById( "canvasImg" ).src = dataURL;
    }
    catch ( err )
    {
        printError( err.stack );
    }
}


// 畫出要儲存的圖片(BMP格式)
function showStoredBmpImage() 
{    
    var ratio = 0.1;
    
    var imageObj = new Image();
    imageObj.onload = function() {
        var width = imageObj.width * ratio;
        var height = imageObj.height * ratio;
        gContext.drawImage( imageObj, 0, 0, width, height );
        var canvasData = readCanvasData( gCanvas, width, height );
        var strData = createBMP( canvasData );
        var dataURL = makeDataURI(strData, "image/bmp");
        
        showStoredDrawing( NOWDO ); // 回歸原圖(把縮小圖刪除)
        
        //var ref = window.open(dataURL, '_blank', 'location=yes');
        //ref.addEventListener('loadstart', function() { showAlert(event.url); });
        
        //saveFile(dataURL);
        document.getElementById( "canvasImg" ).src = dataURL;
    };
    
    storeNowDrawing();
    imageObj.src = getNowDrawing();
}


// generates a <img> object containing the imagedata
var makeImageObject = function(strSource) {
    var oImgElement = document.createElement("img");
    oImgElement.src = strSource;
    return oImgElement;
}

var makeDataURI = function(strData, strMime) {
    var returnValue = "data:" + strMime + ";base64," + strData;
    //printDebug( returnValue );

    return returnValue;
}

// sends the generated file to the client
var saveFile = function(strData) {
    document.location.href = strData;
}

// ok, we're good
var readWholeCanvasData = function(oCanvas) {
    var iWidth = parseInt(oCanvas.width);
    var iHeight = parseInt(oCanvas.height);
    return oCanvas.getContext("2d").getImageData(0,0,iWidth,iHeight);
}

var readCanvasData = function(oCanvas, width, height) {
    return oCanvas.getContext("2d").getImageData(0,0,width,height);
}

// base64 encodes either a string or an array of charcodes
var encodeData = function(data) {
    var strData = "";
    if (typeof data == "string") {
        strData = data;
    } else {
        var aData = data;
        for (var i=0;i<aData.length;i++) {
            strData += String.fromCharCode(aData[i]);
        }
    }
    return btoa(strData);
}


// creates a base64 encoded string containing BMP data
// takes an imagedata object as argument
var createBMP = function(oData) {
    var aHeader = [];

    var iWidth = oData.width;
    var iHeight = oData.height;

    aHeader.push(0x42); // magic 1
    aHeader.push(0x4D); 

    var iFileSize = iWidth*iHeight*3 + 54; // total header size = 54 bytes
    aHeader.push(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
    aHeader.push(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
    aHeader.push(iFileSize % 256); iFileSize = Math.floor(iFileSize / 256);
    aHeader.push(iFileSize % 256);

    aHeader.push(0); // reserved
    aHeader.push(0);
    aHeader.push(0); // reserved
    aHeader.push(0);

    aHeader.push(54); // dataoffset
    aHeader.push(0);
    aHeader.push(0);
    aHeader.push(0);

    var aInfoHeader = [];
    aInfoHeader.push(40); // info header size
    aInfoHeader.push(0);
    aInfoHeader.push(0);
    aInfoHeader.push(0);

    var iImageWidth = iWidth;
    aInfoHeader.push(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
    aInfoHeader.push(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
    aInfoHeader.push(iImageWidth % 256); iImageWidth = Math.floor(iImageWidth / 256);
    aInfoHeader.push(iImageWidth % 256);

    var iImageHeight = iHeight;
    aInfoHeader.push(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
    aInfoHeader.push(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
    aInfoHeader.push(iImageHeight % 256); iImageHeight = Math.floor(iImageHeight / 256);
    aInfoHeader.push(iImageHeight % 256);

    aInfoHeader.push(1); // num of planes
    aInfoHeader.push(0);

    aInfoHeader.push(24); // num of bits per pixel
    aInfoHeader.push(0);

    aInfoHeader.push(0); // compression = none
    aInfoHeader.push(0);
    aInfoHeader.push(0);
    aInfoHeader.push(0);

    var iDataSize = iWidth*iHeight*3; 
    aInfoHeader.push(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
    aInfoHeader.push(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
    aInfoHeader.push(iDataSize % 256); iDataSize = Math.floor(iDataSize / 256);
    aInfoHeader.push(iDataSize % 256); 

    for (var i=0;i<16;i++) {
        aInfoHeader.push(0);	// these bytes not used
    }

    var iPadding = (4 - ((iWidth * 3) % 4)) % 4;

    var aImgData = oData.data;

    var strPixelData = "";
    var y = iHeight;
    do {
        var iOffsetY = iWidth*(y-1)*4;
        var strPixelRow = "";
        for (var x=0;x<iWidth;x++) {
            var iOffsetX = 4*x;

            strPixelRow += String.fromCharCode(aImgData[iOffsetY+iOffsetX+2]);
            strPixelRow += String.fromCharCode(aImgData[iOffsetY+iOffsetX+1]);
            strPixelRow += String.fromCharCode(aImgData[iOffsetY+iOffsetX]);
        }
        for (var c=0;c<iPadding;c++) {
            strPixelRow += String.fromCharCode(0);
        }
        strPixelData += strPixelRow;
    } while (--y);
    
    // 偷偷將畫筆記錄加在圖片最後面
    var strEncoded = encodeData(aHeader.concat(aInfoHeader)) + encodeData(strPixelData + gPenHistory );
    
    //printDebug( strEncoded );

    return strEncoded;
}


function file_viewer_load(controller) 
{
    var s = "Type of files[0]: " + controller.files[0].toString() + "\n" +
        "File name: " + controller.files[0].name + "\n" +
        "File size: " + controller.files[0].size + "\n" +
        "File type: " + controller.files[0].type;
    printDebug( "<6>" + s + "<hr>");

    if ( !window.FileReader ) // 此瀏覽器不支援FileReader
    {
        showAlert( "NOT SUPPORT FileReader !!" );
        return;
    }
    
    var reader = new FileReader();
    reader.readAsDataURL( controller.files[0] );
    
    reader.onloadend =function(event) {
        var filedata = event.target.result;
        //var decode = atob(filedata);
        //var decodedData = atob(filedata);
        var encode = filedata.toString();
        var beginIndex = encode.lastIndexOf( "AAAAA" ); // BMP最後面都補"/" .
        //var de = atob( encode.substring( beginIndex + 5, encode.length ) );
        //printDebug( en + "<br>" );
        //printDebug( de );
        
        //printDebug( "" + beginIndex + "__" + encode.length + "<br>" );
        //printDebug( de );
        //printDebug( atob( encode ) );
        printDebug( "<br>INDEX: " + beginIndex + "," + encode.length ); 
        //printDebug( "<br>CONTENT:" + ( encode.substring( beginIndex + 5, encode.length ) );  
        printDebug( "<br>FILE: " + encode );
        
        
        gPenHistory = de;
        playPenHistory( 0 );
    }
}


